// 复仇模块
package m

import (
	"GameServer/Common/utils"
	"GameServer/Game/cache"
	"GameServer/Game/dbmodule"

	"github.com/globalsign/mgo/bson"
)

type Foe struct {
	BaseM
	Uid     string       `bson:"_id" json:"_id"`
	Members []*FoeMember `bson:"members" json:"members"`
}

type FoeMember struct {
	Uid  string `bson:"uid" json:"uid"`
	Time int64  `bson:"time" json:"time"`
}

func NewFoe() cache.EntryI {
	return &Foe{Members: make([]*FoeMember, 0)}
}

// 保存信息
func (foe *Foe) Save() (err error) {
	if foe.Members == nil || len(foe.Members) == 0 {
		return
	}
	err = dbmodule.MgoDB.GameDB.Upsert("foe", bson.M{"_id": foe.Uid}, foe)
	if err != nil {
		return
	}
	return
}

func (foe *Foe) Load(key interface{}) (err error) {
	foe.Uid = key.(string)
	return foe.LoadData()
}

// 加载数据
func (foe *Foe) LoadData() (err error) {
	err = dbmodule.MgoDB.GameDB.FindOne("foe", bson.M{"_id": foe.Uid}, nil, &foe)
	if err != nil {
		if err.Error() == "not found" {
			return nil
		}
		return
	}
	if foe.Members == nil {
		foe.Members = make([]*FoeMember, 0)
	}
	return
}

// 更新数据
func (foe *Foe) Update(val *Foe) {
	Cache.Put("foe", foe.Uid, val)
	val.UpdateData()
}

// 添加仇人
func (foe *Foe) AddMember(uid string) {
	list := make([]*FoeMember, 0)
	for _, item := range foe.Members {
		if item.Uid == uid {
			continue
		}
		list = append(list, item)
	}

	list = append(list, &FoeMember{Uid: uid, Time: utils.TNow().Unix()})
	if len(list) > 10 {
		list = list[1:]
	}
	foe.Members = make([]*FoeMember, 0)
	foe.Members = list
	foe.Update(foe)
}

// 删除仇人
func (foe *Foe) DelMember(uid string) {
	list := make([]*FoeMember, 0)
	flag := false
	for _, item := range foe.Members {
		if item.Uid == uid {
			flag = true
			continue
		}
		list = append(list, item)
	}
	if flag {
		foe.Members = make([]*FoeMember, 0)
		foe.Members = list
		foe.Update(foe)
	}

}

func (u *User) GetFoe() (r *Foe) {
	v, _ := Cache.Get("foe", u.Uid.Hex())
	r = v.(*Foe)
	return
}
